package com.office.web;

import com.office.bean.Major;
import com.office.bean.MajorType;
import com.office.service.MajorService;
import com.office.service.MajorTypeService;
import com.office.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class MajorController {

    @Autowired
    MajorService majorService;

    @Autowired
    MajorTypeService majorTypeService;


    @RequestMapping("/major_list")
    public String list(long pageIndex, long pageSize, Model model){
        long totalcount = majorService.findTotalcount();
        Map<String , Object> map = new HashMap<>();
        map.put("pageStart",(pageIndex-1)*pageSize);
        map.put("pageSize",pageSize);

        List<Major> majorsByPage = majorService.findMajorsByPage(map);
        PageUtils<Major> pageUtils = new PageUtils<Major>(pageIndex,pageSize,totalcount,majorsByPage);
        model.addAttribute("pageUtils",pageUtils);
        return "majorlist";
    }

    @RequestMapping("/major_del")
    @ResponseBody
    public boolean major_del( int id){
        return majorService.deleteById(id);
    }

    @RequestMapping("/major_update/{id}")
    public String major_update(@PathVariable("id") int id , Model model){
        Major major = majorService.findDepById(id);
        model.addAttribute("major",major);

        return "majorupdate";
    }

    @RequestMapping("/majorupdate")
    public void majorupdate(Major major, HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        int update = majorService.update(major);

        if (update>0){
            response.getWriter().write("<script>alert('更新成功');location.href='/major_list?pageIndex=1&pageSize=5';</script>");

        }else {
            response.getWriter().write("<script>alert('更新失败');location.href='/major_update/"+major.getId()+"';</script>");

        }
    }
    @RequestMapping("/findMajorTypes")
    @ResponseBody
    public List<MajorType> findMajorTypes(){
        return majorTypeService.findMajorTypes();
    }


    @RequestMapping("/major_add")
    public void addmajor(Major major, HttpServletResponse response) throws Exception{

        response.setContentType("text/html;charset=utf-8");
        int i = majorService.addMajor(major);
        if (i>0){
            response.getWriter().write("<script>alert('添加成功');location.href='/major_list?pageIndex=1&pageSize=5';</script>");
        }else {
            response.getWriter().write("<script>alert('添加失败');location.href='/html_majoradd';</script>");
        }
    }
}
